package io.gitee.hefren.hhmq.server;

import io.gitee.hefren.hhmq.model.HhMessage;
import io.gitee.hefren.hhmq.model.Result;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

/**
 * @Date 2024/7/23
 * @Author lifei
 */
@RestController
@RequestMapping(value = "/hhmq")
public class HhMQServer {

    // send
    @RequestMapping(value = "/send", method = RequestMethod.POST)
    public Result<Integer> send(@RequestParam("topic") String topic,
                                @RequestBody HhMessage<?> hhMessage) {
        return Result.ok(HhMQ.sendMessage(topic, hhMessage));
    }

    // subscribe
    @RequestMapping(value = "/subscribe", method = RequestMethod.POST)
    public Result<String> subscribe(@RequestParam("topic") String topic,
                                    @RequestParam("consumerId") String consumerId) {
        HhMQ.subscribeTopic(topic, consumerId);
        return Result.ok(Result.CodeEnum.SUCCESS.name());
    }

    // unsubscribe
    @RequestMapping(value = "/unsubscribe", method = RequestMethod.POST)
    public Result<String> unsubscribe(@RequestParam("topic") String topic,
                                      @RequestParam("consumerId") String consumerId) {
        HhMQ.unsubscribeTopic(topic, consumerId);
        return Result.ok(Result.CodeEnum.SUCCESS.name());
    }

    // receive
    @RequestMapping(value = "/receive", method = RequestMethod.POST)
    public Result<HhMessage<?>> receive(@RequestParam("topic") String topic,
                                        @RequestParam("consumerId") String consumerId) {
        return Result.ok(HhMQ.receiveMessage(topic, consumerId));
    }

    // batchReceive
    @RequestMapping(value = "/batchReceive", method = RequestMethod.POST)
    public Result<List<HhMessage<?>>> batchReceive(@RequestParam("topic") String topic,
                                                  @RequestParam("consumerId") String consumerId,
                                                  @RequestParam("size") Integer size) {
        if (Objects.isNull(size) || size<=0) {
            size = 100;
        }
        return Result.ok(HhMQ.batchReceiveMessage(topic, consumerId,size));
    }

    // ack 确认消费偏移量
    @RequestMapping(value = "/ack", method = RequestMethod.POST)
    public Result<Integer> ack(@RequestParam("topic") String topic,
                               @RequestParam("consumerId") String consumerId,
                               @RequestParam("offset") Integer offset) {
        return Result.ok(HhMQ.ackMessage(topic, consumerId, offset));
    }

}
